<script setup>
import ajax from '@/main';
import {QuestionCircleOutlined, ExclamationCircleOutlined} from '@ant-design/icons-vue';
import {computed, createVNode, onMounted, ref} from "vue";
import {Modal, notification} from "ant-design-vue";

const columns = [
  {
    title: '序号',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: 'IP',
    dataIndex: 'ip',
    key: 'ip',
  },
  {
    title: '组件',
    dataIndex: 'module',
    key: 'module',
  },
  {
    title: '状态',
    key: 'state',
    dataIndex: 'state',
  },
  {
    title: '更新时间',
    key: 'time',
    dataIndex: 'time',
  },
  {
    title: '操作',
    key: 'action',
  },
];

const columnsTask = [
  {
    title: '任务名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '时间段',
    dataIndex: 'time',
    key: 'time',
  }
];

const data = ref([
  {
    id: 1,
    name: 'aaaa',
    ip: ['10.0.1.1', '10.0.1.2'],
    state: 1,
    updatetime: '2024-06-07 14:00:00',
    ipList: []
  },
  {
    id: 2,
    name: 'bbb',
    ip: ['10.0.1.3', '10.0.1.4', '10.0.1.5'],
    state: 0,
    updatetime: '2024-06-06 12:00:00',
    ipList: []
  }
]);

const dataTask = ref([{
  taskName: '任务1',
  timeList: ['01:00', '12:00']
}])

// 增加序号
const dataNew = ref([])

function getServerInfo() {
  ajax.get('/demo/serverManage/serverInfo?pageSize=' + pageSize1.value + '&currentPage=' + current1.value).then(res => {
    if (res.data.code === 200) {
      data.value = res.data.data.data
      total.value = res.data.data.total
      dataNew.value = data.value.map((item, index) => ({
        ...item,
        rowIndex: index, // 添加行号属性
      }));
    } else {
      notification['error']({
        message: '错误提示',
        description: res.data.msg,
      });
    }
  }).catch(err => {
    console.log(err)
  })

}

onMounted(() => {
  getServerInfo();
})

function formatDateTime(dateTimeStr) {
  // 假设dateTimeStr的格式为 "YYYY-MM-DDTHH:mm:ss.sss+00:00"
  // 首先，移除时间字符串中的 "T" 和时区信息
  let dateTimeWithoutTZ = dateTimeStr.replace('T', ' ').replace(/\+\d{2}:\d{2}$/, '');

  // 分离日期和时间
  let [date, time] = dateTimeWithoutTZ.split(' ');

  // 将时间转换为小时、分钟和秒
  let [hours, minutes, seconds] = time.split(':').map(Number);

  // 加上8小时（这里不考虑夏令时或更复杂的时区转换）
  hours = (hours + 8) % 24; // 处理超过24小时的情况

  // 重新组合时间字符串
  let formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

  // 返回最终格式化的日期时间字符串
  return `${date} ${formattedTime}`;
}

const changeAccount = (id, state) => {
  let title;
  let content;
  if (state === 1) {
    content = '恢复后该服务器可正常使用';
    title = '是否要恢复该服务器?';
  } else {
    title = '是否要禁用该服务器?'
    content = '禁用后该服务器将无法使用'
  }
  Modal.confirm({
    title: title,
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
        'div',
        {
          style: 'color:red;',
        },
        content,
    ),
    onOk() {
      ajax.post('/demo/serverManage/changeState', {'id': id, 'state': state}).then(res => {
            if (res.data.code === 200) {
              getServerInfo();

            } else {
              notification['error']({
                message: '失败提示',
                description: res.data.msg,
              });
            }
          }
      )
    },
    onCancel() {
      console.log('Cancel');
    },
    class: 'test',
  });
};


const delAccount = (id) => {
  Modal.confirm({
    title: '确认要删除该服务器吗？',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
        'div',
        {
          style: 'color:red;',
        },
        '删除后服务器信息将被清除',
    ),
    onOk() {
      ajax.post('/demo/serverManage/delServer', {'id': id}).then(res => {
            if (res.data.code === 200) {
              getServerInfo();

            } else {
              notification['error']({
                message: '失败提示',
                description: res.data.msg,
              });
            }
          }
      )
    },
    onCancel() {
      console.log('Cancel');
    },
    class: 'test',
  });
};

const formState = ref({
  name: '',
  timeList: []
})

// 查询服务器
function searchServer() {
  console.log(formState.value)
  ajax.get('/demo/serverManage/searchServer?Name=' + formState.value.name + '&timeList=' + formState.value.timeList +
      '&pageSize=' + pageSize1.value + '&pageNum=' + current1.value).then(res => {
        if (res.data.code === 200) {
          data.value = res.data.data.data
          total.value = res.data.data.total
          dataNew.value = data.value.map((item, index) => ({
            ...item,
            rowIndex: index, // 添加行号属性
          }));

        } else {
          notification['error']({
            message: '失败提示',
            description: res.data.msg,
          });
        }
      }
  )
}

// 添加任务
function addTask(id, name) {
  // 获取相关任务
  ajax.post('/demo/taskManage/taskAbout', {'sid': id}).then(res => {
        if (res.data.code === 200) {
          dataTask.value = res.data.data
        } else {
          notification['error']({
            message: '失败提示',
            description: res.data.msg,
          });
        }
      }
  )
// 获取可选时段
  ajax.get('/demo/taskManage/taskAvailable/' + id).then(res => {
    if (res.data.code === 200) {
      formTask.value.options = res.data.data
    } else {
      notification['error']({
        message: '失败提示',
        description: res.data.msg,
      });
    }
  })

  open2.value = true;
  formTask.value.servername = name
  formTask.value.sid = id
}

const form = ref({
  name: '',
  ipList: [],
  moduleList: [],
});

const formTask = ref({
  taskName: '',
  servername: '',
  sid: 0,
  timeList: [],
  options: [{'label': 'a', 'value': 'a'}, {'label': 'a', 'value': 'a'}, {'label': 'c', 'value': 'c'}],
});

const open = ref(false);
const open2 = ref(false);

// 新增服务器界面
const showDrawer = () => {
  open.value = true;
};
const onClose = () => {
  open.value = false;
};

const onClose2 = () => {
  open2.value = false;
  formTask.value = {}
};

const handleChange = value => {
  console.log(`selected ${value}`);
};

const options = [];
const options3 = [];

const options2 = (() => {
  let r = [];
  for (let h = 0; h < 24; h++) for (let m = 0; m < 60; m += 30) r.push({
    'label': `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`,
    'value': `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`
  });
  return r;
})();

// 新增服务器
function addServer() {
  if (form.value.name.length === 0 || form.value.ipList.length === 0) {
    notification['error']({
      message: '错误提示',
      description: '请检查服务器名称或IP是否输入',
    });
  } else {
    ajax.post('/demo/serverManage/addServer', form.value).then(res => {
      if (res.data.code === 200) {
        open.value = false;
        form.value = {};
        getServerInfo();

      } else {
        notification['error']({
          message: '错误提示',
          description: res.data.msg,
        });
      }
    })
  }
}

// 新增任务
function subTask() {
  if (formTask.value.taskName.length === 0 || formTask.value.timeList.length === 0) {
    notification['error']({
      message: '错误提示',
      description: '请检查服务器名称或时间段是否输入',
    });
  } else {
    ajax.post('/demo/taskManage/subTask', formTask.value).then(res => {
      if (res.data.code === 200) {
        open2.value = false;
        formTask.value = {};
        getServerInfo();

      } else {
        notification['error']({
          message: '错误提示',
          description: res.data.msg,
        });
      }
    })
  }
}

const current1 = ref(1);
const pageSize1 = ref(10);
const total = ref(0);

function changePage() {
  if(formState.value.name.length === 0 && formState.value.timeList.length === 0){
    getServerInfo();
  }else {
    searchServer();
  }
}

</script>

<template>
  <!--search-->
  <a-flex>
    <div class="know-add">
      <a-button type="primary" @click="showDrawer">增加服务器</a-button>
    </div>
    <div class="know-search">
      <a-form
          :model="formState"
          name="horizontal_login"
          layout="inline"
          autocomplete="off"
      >
        <a-form-item
            label="服务器信息"
            name="name"
        >
          <a-input v-model:value="formState.name" placeholder="请输入服务器名称或ip" style="width: 100%;"/>
        </a-form-item>

        <a-form-item
            label="空闲时段"
            name="time">
          <a-select
              v-model:value="formState.timeList"
              mode="tags"
              placeholder="请选择空闲时段"
              style="width: 200px;"
              :options="options2"
          ></a-select>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" @click="searchServer">查询</a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-flex>

  <!--table-->
  <a-table :columns="columns" :data-source="dataNew" :pagination="false" style="margin-top: 20px;">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'id'">
        {{ record.rowIndex + 1 }}
      </template>
      <template v-else-if="column.key === 'name'">
        {{ record.name }}
      </template>
      <template v-else-if="column.key === 'ip'">
        <span>
          <a-tag
              v-for="tag in record.ipList"
              :key="tag"
              color="#2db7f5"
          >
            {{ tag }}
          </a-tag>
        </span>
      </template>
      <template v-else-if="column.key === 'module'">
        <span>
          <a-tag
              v-for="tag in record.moduleList"
              :key="tag"
              color="#36cc80"
          >
            {{ tag }}
          </a-tag>
        </span>
      </template>
      <template v-else-if="column.key === 'state'">
        <span>
          <a-badge v-if="record.state === 0" status="success" text="正常"/>
          <a-badge v-else status="error" text="异常"/>
        </span>
      </template>
      <template v-else-if="column.key === 'time'">
        <span>
          {{ formatDateTime(record.updatetime) }}
        </span>
      </template>
      <template v-else-if="column.key === 'action'">
        <span>
          <a v-if="record.state === 1" @click="changeAccount(record.id, record.state)">启用</a>
          <a v-else @click="changeAccount(record.id, record.state)" style="color: red">禁用</a>
          <a-divider type="vertical"/>
          <a @click="delAccount(record.id)">删除</a>
          <a-divider type="vertical"/>
          <a @click="addTask(record.id, record.name)" v-if="record.state === 0">添加任务</a>
          <a v-else style="color: grey">添加任务</a>
        </span>
      </template>
    </template>
  </a-table>
  <a-pagination
      v-model:current="current1"
      v-model:page-size="pageSize1"
      :total="total"
      :show-total="total => `总计 ${total} 条`"
      class="page-style"
      :showSizeChanger="true"
      @change="changePage"
  />

  <!--新增服务器  -->
  <a-drawer
      title="新增服务器"
      :width="720"
      :open="open"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose"
  >
    <a-form :model="form" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="18">
          <a-form-item label="服务器名称" name="name" :rules="[{ required: true, message: '请输入服务器信息!' }]">
            <a-input v-model:value="form.name" placeholder="请输入服务器名称"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="18">
          <a-form-item label="服务器IP" name="ip" :rules="[{ required: true, message: '' }]">

            <a-select
                v-model:value="form.ipList"
                mode="tags"
                style="width: 100%"
                placeholder="请输入服务IP(支持多ip录入)"
                :options="options"
                @change="handleChange"
            ></a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="18">
          <a-form-item label="服务器组件" name="module" :rules="[{ required: true, message: '' }]">

            <a-select
                v-model:value="form.moduleList"
                mode="tags"
                style="width: 100%"
                placeholder="请输入服务组件"
                :options="options3"
            ></a-select>
          </a-form-item>
        </a-col>
      </a-row>

    </a-form>
    <template #extra>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="addServer">新增</a-button>
      </a-space>
    </template>
  </a-drawer>

  <!--新增任务  -->
  <a-drawer
      title="新增任务"
      :width="720"
      :open="open2"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose2"
  >
    <a-form :model="formTask" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="18">
          <a-form-item label="任务名称" name="name" :rules="[{ required: true, message: '' }]">
            <a-input v-model:value="formTask.taskName" placeholder="请输入任务名称"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="18">
          <a-form-item label="服务器名称" name="servername" :rules="[{ required: true, message: '' }]">
            <a-input v-model:value="formTask.servername" placeholder="请输入服务器名称" disabled/>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="18">
          <a-form-item name="time" :rules="[{ required: true, message: '' }]">
            <template #label>任务时段选择
              <a-popover title="时间段说明">
                <template #content>
                  <p>时间每半小时被划分为一个时间段</p>
                  <p>比如12:00指12:00-12:30这段时间</p>
                </template>
                <QuestionCircleOutlined/>
              </a-popover>
            </template>

            <a-select
                v-model:value="formTask.timeList"
                mode="multiple"
                style="width: 100%"
                placeholder="请选择时间段"
                :options="formTask.options"
                @change="handleChange"
            ></a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <a-table :columns="columnsTask" :data-source="dataTask" style="margin-top: 20px;">
      <template #title>相关任务参考</template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'name'">
          <a>{{ record.taskName }}</a>
        </template>
        <template v-else-if="column.key === 'time'">
        <span>
          <a-tag
              v-for="tag in record.timeList"
              :key="tag"
              color="#2db7f5"
          >
            {{ tag }}
          </a-tag>
        </span>
        </template>
      </template>
    </a-table>
    <template #extra>
      <a-space>
        <a-button @click="onClose2">取消</a-button>
        <a-button type="primary" @click="subTask">新增</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>

<style scoped>
.know-add {
  width: 55%;
}

.know-search {
  width: 45%;
}

.page-style {
  margin-top: 30px;
  float: right;
}

</style>